import React, {useReducer} from 'react';

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return {...state, counter: state.counter + 1}
    case "decrement":
      return {...state, counter: state.counter - 1}
    case "add_number":
      return {...state, counter: state.counter + action.num}
    case "sub_number":
      return {...state, counter: state.counter - action.num}
    default:
      return state
  }
}

const App = () => {
  // const [counter, setCounter] = useState(0)
  //当数据比较复杂的时候，可以使用useReducer，并且统一在reducer中进行逻辑处理（一般用不到）
  const  [state, dispatch]= useReducer(reducer, { counter: 0, friends: [], user: {} });
  //所以，useReducer只是useState的一种替代品，并不能替代redux
  return (
      <div>
        {/*<h2>当前计数:{counter}</h2>*/}
        {/*<button onClick={() => setCounter(counter + 1)}>+1</button>*/}
        {/*<button onClick={() => setCounter(counter - 1)}>-1</button>*/}
        {/*<button onClick={() => setCounter(counter - 1)}>+5</button>*/}
        {/*<button onClick={() => setCounter(counter - 1)}>-5</button>*/}
        {/*<button onClick={() => setCounter(counter - 1)}>+100</button>*/}

        <h2>当前计数:{state.counter}</h2>
        <button onClick={() => dispatch({type: "increment"})}>+1</button>
        <button onClick={() => dispatch({type: "decrement"})}>-1</button>
        <button onClick={() => dispatch({type: "add_number", num: 5})}>+5</button>
        <button onClick={() => dispatch({type: "sub_number", num: 5})}>-5</button>
        <button onClick={() => dispatch({type: "add_number", num: 100})}>+100</button>
      </div>
  );
};

export default App;